package org.cqipc.edu.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.cqipc.edu.common.Constants;
import org.cqipc.edu.dao.LoginLogDao;
import org.cqipc.edu.entity.Login_Log;
import org.cqipc.edu.entity.User;
import org.cqipc.edu.service.UserService;
import org.cqipc.edu.utils.Md5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Description: 登录控制器
 * @ClassName: LoginController
 * @Author: Heyue
 * @DateTime: 2020-06-22
 **/
@Controller
@Transactional
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private LoginLogDao loginLogDao;

    /**
     * @Description: 登录验证
     * @Author: Heyue
     * @Date: 2020/7/2
     */
    @PostMapping("/checkLogin")
    @Transactional(rollbackFor = Exception.class)
    public String checkLogin(String username, String password, boolean rememberMe, HttpSession session) throws UnknownHostException {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, Md5.getMd5(password));
        token.setRememberMe(rememberMe);
        try {
            subject.login(token);
            session.setAttribute("CurrentUser", (User) subject.getSession().getAttribute("UserInfo"));
            Login_Log log = new Login_Log();
            log.setIp(InetAddress.getLocalHost().getHostAddress())
                    .setLoginTime(Constants.CURRENT_TIME)
                    .setLocation("中国|华东|福建省|福州市|联通")
                    .setUsername(((User) session.getAttribute("CurrentUser")).getUsername());
            loginLogDao.addLoginLog(log);
            return "redirect:/index";
        } catch (UnknownAccountException e) {
            return "redirect:/login";
        } catch (IncorrectCredentialsException e) {
            return "redirect:/login";
        }
    }


    /**
     * @Description: 退出登录
     * @Author: Heyue
     * @Date: 2020/6/22
     */
    @GetMapping("/loginOut")
    public Object loginOut() {
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }

}
